package day20170427;

import java.lang.reflect.Method;

import org.junit.Test;

public class MethodTest {
	
	/**
	 * 使用反射，拿到方法
	 * @throws Exception
	 */
	@Test
	public void methodTest() throws Exception {
		//1.拿到照妖镜
		Class clazz = Class.forName("day20170427.Student");
		//获取到学生对象
		Student student = (Student) clazz.newInstance();
		//获取到所有的方法(包括父类的方法)
		Method[] methods = clazz.getMethods();
		for(Method method : methods){
			System.out.println("-------拿到方法名字---------");
			System.out.println(method.getName());
			System.out.println("-------拿到访问修饰符--------");
			System.out.println(method.getModifiers());
			System.out.println("-------拿到返回类型--------");
			System.out.println(method.getReturnType());
		}
		System.out.println("---------getDeclaredMethods----------");
		//拿到的是当前的类所有方法（不包括父类的）
		Method[] declaredMethods = clazz.getDeclaredMethods();
		for(Method method : declaredMethods){
			System.out.println("-------拿到方法名字---------");
			System.out.println(method.getName());
			System.out.println("-------拿到访问修饰符--------");
			System.out.println(method.getModifiers());
			System.out.println("-------拿到返回类型--------");
			System.out.println(method.getReturnType());
		}
		System.out.println("----------getDeclaredMethod(setAge方法)------------");
		Method callerMethod = clazz.getDeclaredMethod("setAge", Integer.class);
		Object invoke = callerMethod.invoke(student, 80);
		System.out.println(student);
		System.out.println("----------getDeclaredMethod(add方法)------------");
		Method add = clazz.getDeclaredMethod("add", int.class,int.class);
		Object addObject = add.invoke(student, 80,80);
		System.out.println(addObject);
	}
}
